package xz.kj.jk.controller;


import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.ocr.AipOcr;
import org.springframework.web.bind.annotation.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import xz.kj.jk.utils.baiduocr.Base64Util;
import xz.kj.jk.utils.baiduocr.FileUtil;
import xz.kj.jk.utils.baiduocr.HttpUtil;
@RestController
@RequestMapping(value = "api/baiduocr")
public class BaiDuOcrController {

    /**
     * 读取磅单信息
     * @param orCode
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping(value = "readBd")
    public Map<String,Object> readBd(@RequestBody Map<String, Object> map) throws Exception {
        String base64Str=map.get("base64Str").toString();
        System.out.println(base64Str);
        Map<String, Object> resultMap = new HashMap<>();
        // 初始化一个AipOcr
         Map<String,Object> postMap=new HashMap<>();

     String accessToken=cn.hutool.http.HttpUtil.post("https://aip.baidubce.com/oauth/2.0/token?client_id=K8n6FFh7sOQRJtUGz2pbPpFh&client_secret=ofKinPkWPZvtZZFLGi9xj7cHMxKgqCIG&grant_type=client_credentials",postMap);
        System.out.println(accessToken);
        JSONObject jsonObject=JSONObject.parseObject(accessToken);
        String accessTokenStr=jsonObject.getString("access_token");
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/weight_note";

//            // 本地文件路径
//            String filePath = "D:\\test.png";
//            // 本地文件路径
//            byte[] imgData = FileUtil.readFileByBytes(filePath);
//            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(base64Str, "UTF-8");

            String param = "image=" + imgParam;

            String result = HttpUtil.post(url, accessTokenStr, param);
            System.out.println(result);
        resultMap.put("data",result);
        return resultMap;
    }

}
